import React, { useEffect, useState } from 'react'
import { Button, Card, Form, Input, Popconfirm, Space, Table, message } from 'antd';
import { SearchOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { ColumnsType } from 'antd/lib/table';
import { HospitalSetItem } from '@/api/hospital/model/hospitalSetTypes';
import { reqBatchRemoveByIds, reqGetHospitalSet, reqRemoveHospitalSet } from '@/api/hospital/hospitalSet';
import { useNavigate } from 'react-router-dom';

export default function HospitalSet() {
  //2. 准备表格的结构
  let columns: ColumnsType<HospitalSetItem> = [
    {
      title: '序号',
      width: 70,
      align: 'center',
      render: (_, record, index) => {
        return index + 1;
      }
    },
    {
      title: '医院名称',
      dataIndex: 'hosname'
    },
    {
      title: '医院编号',
      dataIndex: 'hoscode'
    },
    {
      title: 'API基础路径',
      dataIndex: 'apiUrl'
    },
    {
      title: '签名',
      dataIndex: 'signKey'
    },
    {
      title: '联系人姓名',
      dataIndex: 'contactsName'
    },
    {
      title: '联系人手机号',
      dataIndex: 'contactsPhone'
    },
    {
      title: '操作',
      width: 120,
      fixed: 'right',
      render: (_, record) => {
        return <Space>
          <Button onClick={() => {
            //重定向跳转
            navigate(`/syt/hospital/hospitalSet/edit/${record.id}`)
          }} type="primary" icon={<EditOutlined />}></Button>
          <Popconfirm
            title="确定要删除?"
            onConfirm={async () => {
              //发送请求删除当前 id 的医院
              await reqRemoveHospitalSet(String(record.id));
              //提醒
              message.success('删除成功');
              //更新列表
              setValues({ hoscode: '', hosname: '' })
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button type="primary" danger icon={<DeleteOutlined />}></Button>
          </Popconfirm>
        </Space>
      }
    }
  ];

  //声明医院设置列表的状态
  let [hospitalSet, setHospitalSet] = useState<HospitalSetItem[]>([]);
  //声明与分页相关的状态
  let [current, setCurrent] = useState<number>(1);
  let [total, setTotal] = useState<number>(0);
  let [pageSize, setPageSize] = useState<number>(5);
  //声明加载中的状态
  let [loading, setLoading] = useState<boolean>(false);
  //声明一个状态
  let [values, setValues] = useState({ hoscode: '', hosname: '' });
  //声明状态保存选中医院的 id
  let [selectedIds, setSelectedIds] = useState<number[]>([]);
  //声明一个独立的状态, 用来重新渲染组件
  let [fresh, setFresh] = useState<boolean>(false);
  //useEffect 组件挂载完毕发送请求获取显示的数据
  useEffect(() => {
    let getHospitalSet = async () => {
      //更新状态
      setLoading(true);
      //调用封装的函数
      let result = await reqGetHospitalSet({
        page: current,
        limit: pageSize,
        hosname: values.hosname,
        hoscode: values.hoscode
      });
      //更新医院设置列表的状态
      setHospitalSet(result.records);
      //更新总数的状态
      setTotal(result.total);
      //请求完成, 修改 isloading 为 false
      setLoading(false);
    }
    getHospitalSet();
  }, [current, pageSize, values, fresh]);

  //分页状态改变的回调
  let changePagination = (page: number, pageSize: number) => {
    setCurrent(page);
    setPageSize(pageSize);
  };

  //声明 finish 回调函数
  let finish = (values: any) => {
    //更新状态
    setValues(values);
    //修改页码数
    setCurrent(1);
  }

  //声明 clear 函数 清空按钮的单击事件回调
  let clear = () => {
    //显示无条件的数据结果
    setValues({ hoscode: '', hosname: '' });
  }

  //获取 navigate 函数
  let navigate = useNavigate();

  //声明 batchRemove
  let batchRemove = async () => {
    //发送请求批量删除
    await reqBatchRemoveByIds(selectedIds);
    //成功的提示
    message.success('删除成功');
    //更新状态 重新加载数据
    setFresh(fresh => !fresh);
  }
  return (
    <Card>
      {/* 表单 */}
      <Form
        layout={'inline'}
        onFinish={finish}
      >
        <Form.Item name={'hosname'}>
          <Input placeholder="医院名称" />
        </Form.Item>
        <Form.Item name={'hoscode'}>
          <Input placeholder="医院编号" />
        </Form.Item>
        <Form.Item >
          <Button type="primary" htmlType='submit' icon={<SearchOutlined />}>查询</Button>
        </Form.Item>
        <Form.Item>
          <Button htmlType='reset' onClick={clear}>清空</Button>
        </Form.Item>
      </Form>
      <div className="h-20"></div>
      {/* 两个按钮 */}
      <Space>
        <Button type='primary' onClick={() => {
          navigate('/syt/hospital/hospitalSet/add');
        }}>添加</Button>
        <Button disabled={selectedIds.length === 0} onClick={batchRemove}>批量删除</Button>
      </Space>
      <div className="h-20"></div>
      {/* 表格 */}
      <Table
        bordered
        loading={loading}
        rowKey={'id'}
        rowSelection={{
          type: 'checkbox',
          // selectedRowKeys 选中信息的 id 数组
          // selectedRows 选中的数据数组
          onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
            setSelectedIds(selectedRowKeys as number[]);
          }
        }}
        columns={columns}
        scroll={{ x: 1300 }}
        dataSource={hospitalSet}
        pagination={{
          current: current,
          total: total,
          pageSize: pageSize,
          showSizeChanger: true,
          pageSizeOptions: [5, 10, 15, 20],
          showQuickJumper: true,
          showTotal: (total) => {
            return `总共 ${total} 条数据`
          },
          onChange: changePagination
        }}
      />
    </Card>
  )
}
